Medium
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
1 | Input: [3,2,1,5,6,4] and k = 2 |
Example 2:
1 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 |
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
using Priority Queue
Notice: priority queue is increase order
1 | from queue import PriorityQueue |
Time complexity: O(n log n) insert a element O(log n)
Space complexity: O(n)
我们也可以发现这题本质其实是考察排序,所以有如下一些排序方法
This question ask you to find the kth largest element in the list appearly, but actually it wants you to use different sorted algorithm
Sorted (off the shelf)
Timsort algoritm, 结合了合并排序(merge sort)和插入排序(insertion sort)而得出的排序算法
1 | class Solution: |
Time complexity: O(n log n) because using Timsort
Space complexity: O(n)
- Bubble sorted
1 | class Solution: |
Time complexity: O(n k)
Space complexity: O(n)